
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-11
 * Time: 22:52
 */
class MyThreadPool{
   public int maxPoolSize=0;
    //阻塞队列,用来保存任务
    BlockingQueue<Runnable> queue=new ArrayBlockingQueue<>(1000);
    Queue<Thread> threadQueue=new LinkedList<>();
    public MyThreadPool(int corePoolSize, int maxPoolSize){
        this.maxPoolSize=maxPoolSize;
        //初始化线程池中线程个数,并且执行submit提交的任务
        for (int i = 0; i < corePoolSize; i++) {
        Thread t=new Thread(()->{
            while(true){
                Runnable runnable= null;
                try {
                    runnable = queue.take();
                    runnable.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }



        });
        t.start();
        threadQueue.add(t);
        }


    }
    //把任务添加到线程池中
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
        //此处进行判定.判断当前任务队列的元素个数,是否比较长,
        //如果比较长,说明已有线程,不太能处理过来了,需要创建新的线程
        //如果队列不是很长,没必要创建新的线程

        if(queue.size()>=50&&threadQueue.size()<=maxPoolSize){

            Thread t=new Thread(()->{

                try {
                    while(true){
                        Runnable   runnable2 = queue.take();
                        runnable2.run();
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            });
            t.start();
            threadQueue.add(t);
        }

    }
}
public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
       //核心线程有5个,最大线程数是20
        MyThreadPool myThreadPool=new MyThreadPool(5,20);
        for (int i = 0; i < 10000; i++) {
            int id=i;
            //在main线程中提交线程
            myThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello "+id+" , "+Thread.currentThread().getName());
                }
            });
        }

    }
}
